import datetime
import os
import random

from django.core import serializers
from django.conf import settings
from django.db.models import QuerySet, Q
from django.forms.models import model_to_dict

from Shop.recommendation import recommend
from Store.models import Store
from User.models import MyUser as User
from django.http import HttpResponse, JsonResponse

from django.http import HttpResponse, JsonResponse, HttpResponseNotFound, HttpResponseBadRequest

from django.shortcuts import render
from Shop.models import Commodity, Address, Order, OrderShip, CartShip, Cart, Favorite
from Shop.models import Favorite as ShopFavorite
import json

# Create your views here.
import base64
import urllib
import requests


def get_file_content_as_base64(file, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """
    content = base64.b64encode(file.read()).decode("utf8")
    if urlencoded:
        content = urllib.parse.quote_plus(content)
    return content


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    API_KEY = "g7nymWfuVxSrMTy6MaWgtPdA"
    SECRET_KEY = "uenUi2CLHAap8amQ28HLVr0GRVHkotUz"

    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def pictureSearch(request):
    # 获取前端发来的的file对象
    file = request.FILES.get('file')
    # 先判断用户的文件是否存在,存在则覆盖原图片
    print("来撒")
    url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=" + get_access_token()

    # image 可以通过 get_file_content_as_base64("C:\fakepath\抗原检测2.jpg",True) 方法获取
    # payload='image=%2F9j%2F4SOKRXhpZgAATU0AKgAAAAgABgESAAMAAAABAAEAAAEaAAUAAAABAAAAVgEbAAUAAAABAAAAXgEoAAMAAAABAAIAAAIT...&baike_num=0'
    payload = "image=" + get_file_content_as_base64(file, True)
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    data = json.loads(response.text)
    return JsonResponse({'result': data['result'][0]['keyword']}, json_dumps_params={"ensure_ascii": False})


def listProducts(request):
    # 参数获取
    category_first_id = request.GET.get('category_first_id', '0')
    category_second_id = request.GET.get('category_second_id', '0')
    start = request.GET.get('start', '0')
    limit = request.GET.get('limit', '10')

    # 类别获取
    category_first_dict = {'0': '数码', '1': '家电', '2': '配件', '3': '食品', '4': '图书', '5': '其他'}
    category_second_dict = {'数码': {'0': '手机', '1': '电脑', '2': '平板', '3': '耳机', '4': '其他'},
                            '家电': {'0': '电视', '1': '冰箱', '2': '洗衣机', '3': '空调', '4': '其他'},
                            '配件': {'0': '手机配件', '1': '电脑配件', '2': '平板配件', '3': '耳机配件', '4': '其他'}
                            }
    category_first = category_first_dict[category_first_id]
    category_second = category_second_dict[category_first][category_second_id]

    res = Commodity.objects.filter(category_first=category_first, category_second=category_second)[
          int(start):int(start) + int(limit)].values()
    res = list(res)
    # 把商品中的id字段改为commodity_id
    for commodity in res:
        commodity['commodity_id'] = commodity.pop('id')
    if res is None:
        return HttpResponse('无相应数据')
    data = {'items': res, 'total': len(res)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def SortProducts(request):
    # 参数获取
    category_first_id = request.GET.get('category_first_id')
    start = request.GET.get('start', '0')
    limit = request.GET.get('limit', '10')
    # 类别获取
    category_first_dict = {'1': '数码', '2': '家电', '3': '配件', '4': '食品', '5': '图书', '6': '其他'}
    category_first = category_first_dict[category_first_id]
    print(category_first)
    lenth = Commodity.objects.filter(category_first=category_first).values()
    res = Commodity.objects.filter(category_first=category_first)[int(start):int(start) + int(limit)].values()
    for commodity in res:
        commodity['commodity_id'] = commodity.pop('id')
    if res is None:
        return HttpResponse('无相应数据')
    data = {'items': list(res), 'total': len(lenth)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def GetAllProducts(request):
    start = request.GET.get('start', '0')
    limit = request.GET.get('limit', '10')
    length = Commodity.objects.filter().values()
    res = Commodity.objects.filter()[int(start):int(start) + int(limit)].values()
    if res is None:
        return HttpResponse('无相应数据')
    res = list(res)
    # 把商品中的id字段改为commodity_id
    for commodity in res:
        commodity['commodity_id'] = commodity.pop('id')
    data = {'items': res, 'total': len(length)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def GetPayOrders(request):
    user_id = request.GET.get('user_id')
    status = request.GET.get('type')
    start = request.GET.get('start', '0')
    limit = request.GET.get('limit', '5')
    user = User.objects.get(id=user_id)
    print(status)
    item2 = []
    if status == '0':
        total = Order.objects.filter(~Q(status_buyer='已取消') &~Q(status_buyer='已完成'),user=user).values()
        OrderUser = OrderShip.objects.filter(~Q(order__status_buyer='已取消') &~Q(order__status_buyer='已完成'),order__user=user)[
                    int(start):int(start) + int(limit)].values()
        item = Order.objects.filter(~Q(status_buyer='已取消') &~Q(status_buyer='已完成'),user=user)[int(start):int(start) + int(limit)]

    elif (status == '1'):
        total = Order.objects.filter(user=user, status_buyer='待付款').values()
        OrderUser = OrderShip.objects.filter(order__user=user, order__status_buyer='待付款')[
                    int(start):int(start) + int(limit)].values()
        item = Order.objects.filter(user=user, status_buyer='待付款')[int(start):int(start) + int(limit)]


    elif (status == '2'):
        total = Order.objects.filter(user=user, status_buyer='已付款').values()
        OrderUser = OrderShip.objects.filter(order__user=user, order__status_buyer='已付款')[
                    int(start):int(start) + int(limit)].values()
        item = Order.objects.filter(user=user, status_buyer='已付款')[int(start):int(start) + int(limit)]

    else:
        total = Order.objects.filter(Q(status_buyer='已取消') | Q(status_buyer='已完成'), user=user).values()
        OrderUser = OrderShip.objects.filter(Q(order__status_buyer='已取消') |Q(order__status_buyer='已完成'),
                                        order__user=user)[
                    int(start):int(start) + int(limit)].values()
        item = Order.objects.filter(Q(status_buyer='已取消') | Q(status_buyer='已完成'), user=user)[
               int(start):int(start) + int(limit)]
    if item is None:
        return HttpResponse('无相应数据')

    commodity_list = []
    for i in item:
        commodity_list.append(list(i.related_commodity.all().values()))

    item_list = list(item.values())
    for i in range(len(item_list)):
        item_list[i]['commodity'] = commodity_list[i][0]

    data = {'items': item_list, 'item2': list(OrderUser), 'total': len(total)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def GetOrderDetail(request):
    order_id = request.GET.get('order_id')
    print(order_id)
    item = Order.objects.filter(id=order_id).values()
    item2 = OrderShip.objects.filter(id=order_id).values()
    if item is None:
        return HttpResponse('无相应数据')
    data = {'items': list(item), 'item2': list(item2)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def getAddress(request):
    user_id = request.GET.get('user_id')
    print(user_id)
    user = User.objects.get(id=user_id)
    address = Address.objects.filter(user=user).values()
    if address is None:
        return HttpResponse('无相应数据')
    data = {'addresses': list(address), 'total': len(address)}
    print(data)
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def GetDetailAddress(request):
    user_id = request.GET.get('user_id')
    address_id = request.GET.get('address_id')
    print(user_id)
    user = User.objects.get(id=user_id)
    address = Address.objects.filter(user=user, id=address_id).values()
    if address is None:
        return HttpResponse('无相应数据')
    data = {'addresses': list(address)}
    print(data)
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def updateAddress(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    address_id = data.get('id')  # id就是地址的id

    new_address = data.get('address')
    new_nickname = data.get('nickname')
    new_phone = data.get('phone')
    user = User.objects.get(id=user_id)
    address = Address.objects.filter(id=address_id)

    if address is None:
        return HttpResponse("无该用户的地址数据", status=404)
    address.update(user=user, address=new_address, nickname=new_nickname, phone=new_phone)
    return HttpResponse('success')


def addAddress(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    address = data.get('address')
    nickname = data.get('nickname')
    phone = data.get('phone')
    user = User.objects.get(id=user_id)
    Address.objects.create(user=user, address=address, nickname=nickname, phone=phone)
    return HttpResponse('success')


def deleteAddress(request):
    id = request.GET.get('id')
    print(id)
    Address.objects.filter(id=id).delete()
    return HttpResponse('success')


def exitOrder(request):
    user_id = request.GET.get('user_id')
    order_id = request.GET.get('order_id')
    OrderShip.objects.filter(id=order_id).delete()
    Order.objects.filter(id=order_id).delete()
    return HttpResponse(status=200)


def createOrder(request):
    # 获取多个商品的id和数量
    data = json.loads(request.body.decode('utf-8'))

    user_id = data.get('user_id')
    address_id = data.get('address_id')
    commodity_list = data.get('commodity_list')
    print(commodity_list)
    order_list = []
    for commodity in commodity_list:
        comd = Commodity.objects.get(id=commodity['commodity_id'])
        store_id = Commodity.objects.get(id=commodity['commodity_id'])
        merchant_id = Store.objects.get(id=store_id.store_id)
        order = Order()
        order.user_id = user_id
        order.merchant_id = merchant_id.user_id
        order.address = Address.objects.get(id=address_id)
        order.created_at = datetime.datetime.now()
        order.status_buyer = '待付款'
        order.status_merchant = '待发货'
        order.save()
        order_list.append(order.id)
        OrderShip.objects.create(order=order, commodity=comd, quantity=commodity['quantity'],
                                 subtotal=commodity['quantity'] * comd.current_price)

    return JsonResponse({'order_list': order_list, 'total': len(order_list)}, json_dumps_params={"ensure_ascii": False})


def CompleteOrder(request):
    user_id = request.GET.get('user_id')
    order_id = request.GET.get('order_id')
    order=Order.objects.get(id=order_id)
    order.status_buyer='已完成'
    order.status_merchant='已完成'
    try:
        order.save()
        return HttpResponse(status=200)
    except:
        return HttpResponse(status=404)

def searchGoods(request):
    data = json.loads(request.body.decode('utf-8'))
    name = data.get('name')
    start = data.get('start')
    limit = data.get('limit')
    total = len(Commodity.objects.filter(name__contains=name))
    res = Commodity.objects.filter(name__contains=name)[int(start):int(start) + int(limit)].values()
    if res is None:
        return HttpResponse("无数据", status=404)
    print(total)
    data = {'items': list(res), 'total': total}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def showProduct(request):
    id = request.GET.get('id', None)
    if id is None:
        return HttpResponseBadRequest('无相应数据')
    res = Commodity.objects.filter(id=id).values().first()
    if res is None:
        return HttpResponseNotFound('无相应数据')

    return JsonResponse(res, json_dumps_params={"ensure_ascii": False})


def changeOrder(request):
    order_id = request.GET.get('order_id')
    user_id = request.GET.get('user_id')
    order = Order.objects.get(user_id=user_id, id=order_id)
    order.status_buyer = '已取消'
    try:
        order.save()
        return HttpResponse(status=200)
    except:
        return HttpResponse(status=404)


def showPictures(request):
    id = request.GET.get('id', None)
    if id is None:
        return HttpResponseBadRequest('无相应数据')
    res = Commodity.objects.filter(id=id).values().first()
    if res is None:
        return HttpResponseNotFound('无相应数据')

    data = {'img1': res['img1'], 'img2': res['img2'], 'img3': res['img3']}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def Save_commodity(request):
    # image_path = os.path.join(settings.MEDIA_ROOT, 'image/test.jpg')
    # with open(image_path, 'rb') as img_file:
    #     comd=Commodity.objects.create(name='牛肉', description='牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉牛肉',
    #                                   category_first='食品', category_second='肉类', color='红色',
    #                                   parameters='100g', original_price=100, current_price=80, stock=100)
    #     comd.img1.save('test.jpg', img_file)
    #     comd.img2.save('test.jpg', img_file)
    #     comd.img3.save('test.jpg', img_file)
    # 一行一行读取../media/100_data.json
    cnt = 0
    with open('media/100_data.json', 'r', encoding='utf-8') as f:
        for line in f:
            cnt += 1
            if cnt % 20 == 0:
                print(cnt)
            data = json.loads(line)
            good_name = data['商品名']
            good_id = data['商品ID']
            good_category_first = data['商品分类(一级)']
            good_category_second = data['商品分类(二级)']
            good_description = data['商品简述']
            good_parameters = data['商品参数']
            good_original_price = data['商品原价']
            good_current_price = data['商品现价']
            good_turnover = data['商品成交量']
            good_stock = data['商品库存量']

            comd = Commodity.objects.create(name=good_name, description=good_description,
                                            category_first=good_category_first, category_second=good_category_second,
                                            parameters=good_parameters, original_price=good_original_price,
                                            current_price=good_current_price, turnover=good_turnover, stock=good_stock)
            with open(f"{settings.MEDIA_ROOT}/images/{good_id}_{1}.jpg", 'rb') as img_file:
                comd.img1.save(f"{good_id}_{1}.jpg", img_file)
            with open(f"{settings.MEDIA_ROOT}/images/{good_id}_{2}.jpg", 'rb') as img_file:
                comd.img2.save(f"{good_id}_{2}.jpg", img_file)
            with open(f"{settings.MEDIA_ROOT}/images/{good_id}_{3}.jpg", 'rb') as img_file:
                comd.img3.save(f"{good_id}_{3}.jpg", img_file)

    return HttpResponse('success')


def addCart(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    commodity_id = data.get('commodity_id')
    print(user_id, commodity_id)

    user = User.objects.get(id=user_id)
    commodity = Commodity.objects.get(id=commodity_id)
    cart = Cart.objects.filter(user=user).first()

    if cart is None:
        cart = Cart.objects.create(user=user)
    cartship = CartShip.objects.filter(cart=cart, commodity=commodity).first()
    if cartship is None:  # 说明该用户的购物车中没有该商品，需要新创建
        CartShip.objects.create(cart=cart, commodity=commodity, quantity=1)
        dict_commodity = model_to_dict(commodity)
        dict_commodity['quantity'] = 1
        dict_commodity['img1'] = commodity.img1.url
        dict_commodity['img2'] = commodity.img2.url
        dict_commodity['img3'] = commodity.img3.url
        # 将原本字典中的id改为commodity_id
        dict_commodity['commodity_id'] = dict_commodity.pop('id')
        print(dict_commodity)
        return JsonResponse(dict_commodity, json_dumps_params={"ensure_ascii": False}, status=200)
        # return HttpResponse(status=404)
    else:
        try:
            cartship.quantity += 1
            cartship.save()
            return HttpResponse(status=201)
        except:
            return HttpResponse(status=404)


def updateCart(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    commodity_id = data.get('commodity_id')
    quantity = data.get('quantity')
    print(user_id, commodity_id, quantity)

    user = User.objects.get(id=user_id)
    commodity = Commodity.objects.get(id=commodity_id)
    cart = Cart.objects.get(user=user)
    cartship = CartShip.objects.get(cart=cart, commodity=commodity)
    try:
        cartship.quantity = quantity
        cartship.save()
        return HttpResponse(status=200)
    except:
        return HttpResponse(status=404)


def deleteCart(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    commodity_id = data.get('commodity_id')
    user = User.objects.get(id=user_id)
    commodity = Commodity.objects.get(id=commodity_id)
    cart = Cart.objects.get(user=user)
    cartship = CartShip.objects.get(cart=cart, commodity=commodity)
    print(user_id, commodity_id)
    try:
        cartship.delete()
        print()
        return HttpResponse(status=200)
    except:
        return HttpResponse(status=404)


def showCart(request):
    user_id = request.GET.get('user_id')
    user = User.objects.get(id=user_id)
    # User -> Cart-> CartShip
    user_carts = CartShip.objects.filter(cart__user=user)  # 外键关联查询
    user_commodity = []
    for user_cart in user_carts:
        commodity = model_to_dict(user_cart.commodity)
        commodity['quantity'] = user_cart.quantity
        commodity['stock'] = user_cart.commodity.stock
        commodity['img1'] = user_cart.commodity.img1.url
        commodity['img2'] = user_cart.commodity.img2.url
        commodity['img3'] = user_cart.commodity.img3.url
        # 将原本字典中的id改为commodity_id
        commodity['commodity_id'] = commodity.pop('id')
        user_commodity.append(commodity)
        print(commodity)

    # if user_cart is None:
    #     return HttpResponse(status=404)
    data = {'items': list(user_commodity), 'total': len(user_commodity)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def addFavorite(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    commodity_id = data.get('commodity_id')
    print(user_id, commodity_id)

    user = User.objects.get(id=user_id)
    commodity = Commodity.objects.get(id=commodity_id)

    # 检查用户是否已经有收藏夹
    favorite = Favorite.objects.filter(user=user, commodity=commodity).first()
    if favorite is None:
        favorite = Favorite.objects.create(user=user)
        favorite.commodity.add(commodity)
        return HttpResponse("成功添加至收藏夹", status=200)
    else:
        return HttpResponse("该商品已经在收藏夹中", status=200)


def deleteFavorite(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    commodity_id = data.get('commodity_id')
    user = User.objects.get(id=user_id)
    commodity = Commodity.objects.get(id=commodity_id)
    favorites = Favorite.objects.filter(user=user)
    removed = False
    for favorite in favorites:
        print(favorite)
        if favorite.commodity.filter(id=commodity_id).exists():
            favorite.commodity.remove(commodity)
            removed = True
        if not favorite.commodity.exists():
            favorite.delete()
    if removed:
        return HttpResponse(status=200)
    else:
        return HttpResponse(status=404)


def showFavorites(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = data.get('user_id')
    start = data.get('start', '0')
    limit = data.get('limit', '10')

    # 查询Favorite表中该用户收藏的商品id
    commodities = Commodity.objects.filter(favorite__user_id=user_id).values()
    res = list(commodities)
    # 把商品中的id字段改为commodity_id
    for commodity in res:
        commodity['commodity_id'] = commodity.pop('id')

    if res is []:
        return HttpResponse('无相应数据', status=404)
    else:
        res = res[int(start):int(start) + int(limit)]

    data = {'items': res, 'total': len(res)}
    return JsonResponse(data, json_dumps_params={"ensure_ascii": False})


def test(request):
    vue = json.loads(request.body.decode('utf-8'))
    user_id = vue.get('user_id')
    num = vue.get('num')
    print("lyy")
    try:
        co_list=recommend(user_id,num)
    except:
        co_list=Commodity.objects.all()
        x=random.randint(0,len(co_list)-num)
        co_list=co_list[x:x+num]
    res = []
    for commodity in co_list:
        dict_commodity = model_to_dict(commodity)
        dict_commodity ['img1'] = commodity.img1.url
        dict_commodity ['img2'] = commodity.img2.url
        dict_commodity ['img3'] = commodity.img3.url
        res.append(dict_commodity)
    for comm in res:
        comm['commodity_id'] = comm.pop('id')
    print(len(res))
    return JsonResponse({'items': list(res), 'total': len(res)},
                        json_dumps_params={"ensure_ascii": False})




